Working with Multiple Catch Blocks in Java
Course: Core Java Training
Topic: Working with Multiple Catch Blocks
Course Link: Core Java Training Course
Demo Link: Register for a Course Demo
JustAcademy Website: Visit JustAcademy
1. Introduction to Multiple Catch Blocks
Exception handling is an important feature of Java that allows developers to manage runtime problems without unnecessarily terminating program execution. A single try block may contain statements that can produce different types of exceptions. Java allows developers to handle these exceptions separately by using multiple catch blocks.
Each catch block specifies the type of exception it can handle. When an exception occurs, Java searches the associated catch blocks in order and executes the first compatible handler. The remaining catch blocks are skipped for that exception.
For example, a program that performs arithmetic calculations and accesses an array might encounter an ArithmeticException or an ArrayIndexOutOfBoundsException. Multiple catch blocks allow the program to respond appropriately to each problem.
2. Learning Objectives
- Understand the purpose of multiple catch blocks.
- Learn the syntax of multiple catch blocks in Java.
- Understand how Java selects the matching catch block.
- Differentiate between specific and general exception handlers.
- Learn the correct order of catch blocks.
- Understand the difference between multiple catch blocks and multi-catch.
- Explore practical Java programs using exception handling.
- Identify common mistakes and apply exception-handling best practices.
3. What Is a Catch Block?
A catch block is a section of code that handles an exception thrown from its associated try block. It receives the exception object through a parameter and executes the statements defined inside the block.
The general syntax is:
try {
// Code that may throw an exception
} catch (ExceptionType e) {
// Handle the specified exception
}
In this syntax:
try contains the code that may cause an exception.
catch identifies the exception type to handle.
ExceptionType is the class of exception being handled.
e is a reference to the exception object.
4. What Are Multiple Catch Blocks?
Multiple catch blocks are two or more catch clauses associated with the same try block. They allow a program to handle different exception types using separate handling logic.
Multiple catch blocks are useful when different failures require different responses, such as displaying a specific message for invalid array access and another message for division by zero.
Basic Syntax
try {
// Statements that may throw exceptions
} catch (ExceptionType1 e) {
// Handle the first exception type
} catch (ExceptionType2 e) {
// Handle the second exception type
} catch (ExceptionType3 e) {
// Handle the third exception type
}
A single try block can have multiple catch blocks, but only the first compatible catch block is executed for a particular exception. If no catch block matches, the exception propagates to the calling method unless handled elsewhere.
5. How Multiple Catch Blocks Work
Java uses the type of the thrown exception object to determine which catch block should execute.
- The program enters the
try block.
- The statements execute until the block finishes or an exception occurs.
- If an exception occurs, Java checks the catch blocks in their declared order.
- The first compatible catch block handles the exception.
- The remaining catch blocks associated with that try statement are skipped.
- After the selected catch block completes, execution continues after the complete try-catch structure, unless the handler transfers control in another way.
If no exception occurs, none of the catch blocks executes.
6. Example 1: Handling ArithmeticException and ArrayIndexOutOfBoundsException
public class MultipleCatchExample {
public static void main(String[] args) {
int[] numbers = {10, 20, 30};
try {
int result = 100 / 0;
System.out.println(result);
System.out.println(numbers[5]);
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero.");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Invalid array index.");
}
System.out.println("Program continues.");
}
}
Output
Cannot divide by zero.
Program continues.
Explanation
The first operation attempts to divide 100 by zero, causing an ArithmeticException. Java executes the first catch block that matches this exception. The statement accessing the array is never reached because execution leaves the try block when the exception occurs.
The second catch block is available for an array-index exception if that exception occurs during another execution of the try block. It does not execute for the arithmetic exception.
7. Example 2: Handling an Array Exception
public class ArrayCatchExample {
public static void main(String[] args) {
int[] values = {5, 10, 15};
try {
System.out.println(values[1]);
System.out.println(values[8]);
} catch (ArithmeticException e) {
System.out.println("Arithmetic operation failed.");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("The requested array index is invalid.");
}
System.out.println("Execution completed.");
}
}
Output
10
The requested array index is invalid.
Execution completed.
Explanation
The first array access is valid and prints 10. The second access attempts to retrieve an element at index 8, which is outside the array's valid range. Java executes the ArrayIndexOutOfBoundsException handler and continues after the try-catch structure.
8. Example 3: Handling NumberFormatException and NullPointerException
public class StringExceptionExample {
public static void main(String[] args) {
String number = "abc";
String text = null;
try {
int value = Integer.parseInt(number);
System.out.println(value);
System.out.println(text.length());
} catch (NumberFormatException e) {
System.out.println("The supplied text is not a valid integer.");
} catch (NullPointerException e) {
System.out.println("The string reference is null.");
}
System.out.println("Program execution completed.");
}
}
Output
The supplied text is not a valid integer.
Program execution completed.
Explanation
The string "abc" cannot be converted into an integer, so Integer.parseInt() throws a NumberFormatException. The first matching catch block handles the exception.
The call to text.length() is never reached. Therefore, the NullPointerException catch block does not execute in this run.
9. Ordering of Catch Blocks
The order of catch blocks is important when an exception class has subclasses. A catch block for a superclass can also catch exceptions belonging to its subclasses.
Therefore, place more specific exception types before more general exception types.
Correct Ordering
try {
int result = 10 / 0;
System.out.println(result);
} catch (ArithmeticException e) {
System.out.println("Arithmetic error occurred.");
} catch (Exception e) {
System.out.println("Another exception occurred.");
}
In this example, ArithmeticException is more specific than Exception, so it appears first.
Incorrect Ordering
try {
int result = 10 / 0;
System.out.println(result);
} catch (Exception e) {
System.out.println("General exception.");
} catch (ArithmeticException e) {
System.out.println("Arithmetic exception.");
}
Why is this incorrect? The first catch block already handles ArithmeticException because it is a subclass of Exception. The later ArithmeticException block is unreachable, so the compiler reports an error.
Common Exception Relationships
| Specific Exception |
General Parent |
FileNotFoundException |
IOException |
ArithmeticException |
RuntimeException |
NullPointerException |
RuntimeException |
ArrayIndexOutOfBoundsException |
IndexOutOfBoundsException |
RuntimeException |
Exception |
10. Using a General Exception Handler
A general catch block such as catch (Exception e) can handle many exception types that extend Exception. It is often used as a fallback after more specific handlers.
public class GeneralCatchExample {
public static void main(String[] args) {
try {
String value = null;
System.out.println(value.length());
} catch (NullPointerException e) {
System.out.println("A required value is missing.");
} catch (Exception e) {
System.out.println("An unexpected exception occurred.");
}
}
}
Output
A required value is missing.
Explanation: The first catch block handles the NullPointerException. The general handler is not executed because the exception has already been handled.
Important: catch (Exception e) does not catch every possible throwable. In particular, it does not catch instances of Error, because Error and Exception are separate subclasses of Throwable.
11. Multiple Catch Blocks vs. Multi-Catch
Multiple catch blocks use separate handlers for different exception types. Java 7 introduced multi-catch, which allows a single catch block to handle several unrelated exception types when they require the same handling logic.
Multiple Catch Blocks
try {
// Perform an operation
} catch (NumberFormatException e) {
System.out.println("Invalid numeric input.");
} catch (NullPointerException e) {
System.out.println("A required value is missing.");
}
Multi-Catch Syntax
try {
// Perform an operation
} catch (NumberFormatException | NullPointerException e) {
System.out.println("Input processing failed: " + e.getMessage());
}
Use separate catch blocks when each exception requires a different response. Use multi-catch when several unrelated exception types can be handled with the same logic.
| Feature |
Multiple Catch Blocks |
Multi-Catch |
| Structure |
Separate catch clauses. |
One catch clause with multiple exception types separated by |. |
| Handling logic |
Can differ for each exception. |
Shared by the listed exception types. |
| Introduced |
Available in early Java versions. |
Introduced in Java 7. |
| Exception relationships |
Specific handlers must precede broader handlers. |
Listed types cannot be related to one another through subclassing. |
12. Using Multiple Catch Blocks with User Input
The following example demonstrates how multiple catch blocks can help handle invalid numeric input and division by zero.
import java.util.Scanner;
public class CalculatorExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try {
System.out.print("Enter the first integer: ");
int first = Integer.parseInt(scanner.nextLine());
System.out.print("Enter the second integer: ");
int second = Integer.parseInt(scanner.nextLine());
int result = first / second;
System.out.println("Result: " + result);
} catch (NumberFormatException e) {
System.out.println("Please enter valid integers.");
} catch (ArithmeticException e) {
System.out.println("The second integer must not be zero.");
} finally {
scanner.close();
}
}
}
Possible Output 1
Enter the first integer: 20
Enter the second integer: 4
Result: 5
Possible Output 2
Enter the first integer: abc
Please enter valid integers.
Possible Output 3
Enter the first integer: 20
Enter the second integer: 0
The second integer must not be zero.
Explanation: Invalid integer text causes a NumberFormatException, while dividing an integer by zero causes an ArithmeticException. Each exception is handled by its corresponding catch block. The finally block closes the scanner after the try-catch structure exits.
Note: Closing a scanner created around System.in also closes the underlying standard input stream. In larger applications, manage shared input resources carefully.
13. Relationship Between try, catch, and finally
Java exception handling commonly uses the try, catch, and finally constructs.
- try: Contains statements that may throw exceptions.
- catch: Handles a matching exception type.
- finally: Provides cleanup code that normally executes when control leaves the try-catch structure, whether an exception occurs or not.
try {
System.out.println("Inside try block.");
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Exception handled.");
} catch (Exception e) {
System.out.println("General exception handled.");
} finally {
System.out.println("Finally block executed.");
}
Output
Inside try block.
Exception handled.
Finally block executed.
The arithmetic exception is handled by the first catch block. The general catch block is skipped, and the finally block executes afterward.
14. Benefits of Multiple Catch Blocks
- Specific handling: Each exception can receive a suitable response.
- Improved readability: The handling logic is organized by exception type.
- Better debugging: Messages can identify the nature of the problem.
- Improved user experience: Users can receive more meaningful feedback.
- Controlled execution: Expected failures can be handled without abruptly terminating the normal flow.
- Easier maintenance: Developers can update handling logic for individual exception types.
15. Common Mistakes to Avoid
| Mistake |
Problem |
Recommended Solution |
| Placing a general catch block first |
More specific catch blocks afterward may become unreachable. |
Order handlers from specific to general. |
| Assuming every catch block executes |
Only the first matching handler executes for a given exception. |
Understand exception matching and control flow. |
| Using empty catch blocks |
Failures may go unnoticed. |
Handle, log, or propagate exceptions appropriately. |
| Catching the wrong exception type |
The exception may remain unhandled by the current try statement. |
Choose handlers based on the operations performed. |
| Using exceptions instead of input validation |
Normal invalid conditions may be unnecessarily expensive or confusing to handle. |
Validate inputs before performing operations where appropriate. |
| Duplicating identical catch logic |
Repeated code makes maintenance harder. |
Consider multi-catch for unrelated exception types with identical handling. |
| Catching overly broad types without a reason |
Unexpected failures may be hidden or mishandled. |
Catch only exceptions that the current layer can handle meaningfully. |
16. Practical Exercises
Exercise 1: Arithmetic Operations
Create a program that divides two integers. Use separate catch blocks for ArithmeticException and NumberFormatException.
Exercise 2: Array Access
Create an integer array and ask the user to enter an index. Handle ArrayIndexOutOfBoundsException if the index is invalid.
Exercise 3: String Conversion
Convert a string into an integer and handle invalid input using NumberFormatException. Add another handler for a different exception that can genuinely arise in your chosen code.
Exercise 4: Correct Catch Ordering
Write a program that handles FileNotFoundException, IOException, and a general Exception. Arrange the catch blocks in the correct order.
Exercise 5: Compare Multi-Catch
Write one program with separate catch blocks and another using multi-catch for unrelated exception types that require identical handling. Compare the readability of both versions.
17. Mini Project: Simple Student Marks Calculator
Objective: Build a marks calculator that accepts numeric input, calculates an average, and handles common input and calculation problems.
public class MarksCalculator {
public static void main(String[] args) {
String[] marksInput = {"80", "90", "invalid"};
try {
int first = Integer.parseInt(marksInput[0]);
int second = Integer.parseInt(marksInput[1]);
int third = Integer.parseInt(marksInput[2]);
int total = first + second + third;
double average = total / 3.0;
System.out.println("Average marks: " + average);
} catch (NumberFormatException e) {
System.out.println("Marks must contain valid numbers.");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Required marks are missing.");
} catch (Exception e) {
System.out.println("An unexpected problem occurred.");
}
}
}
Expected Output
Marks must contain valid numbers.
Project Explanation
The third value is not a valid integer, so parsing causes a NumberFormatException. The matching catch block handles it. The array exception handler is available if an accessed index is missing, while the general exception handler serves as a final fallback.
Enhancement tasks:
- Read marks from the keyboard.
- Validate that each mark is between 0 and 100.
- Display the total and average for valid values.
- Create a custom checked exception for invalid marks.
- Display clear messages for each invalid condition.
18. Interview Questions and Answers
Q1. What are multiple catch blocks in Java?
Answer: Multiple catch blocks are several catch clauses associated with one try block. Each can handle a different exception type.
Q2. Can one try block have multiple catch blocks?
Answer: Yes. A try block can be followed by multiple catch blocks to handle different exceptions separately.
Q3. How many catch blocks execute for one thrown exception?
Answer: Only the first compatible catch block executes for that exception.
Q4. Why must specific catch blocks come before general catch blocks?
Answer: A general handler can also catch instances of its subclasses. Placing it first may make a later, more specific handler unreachable.
Q5. Can we use catch(Exception e) as the only handler?
Answer: Yes, when appropriate, but it handles exceptions that extend Exception, not all throwable types. More specific handlers are often preferable when different failures require different responses.
Q6. What is the difference between multiple catch and multi-catch?
Answer: Multiple catch uses separate handlers, which may contain different logic. Multi-catch uses one handler for several unrelated exception types that share the same handling logic.
Q7. What happens if no catch block matches?
Answer: The exception propagates to the calling method. If no suitable handler is found, it remains uncaught for that thread.
Q8. Can catch blocks appear before the try block?
Answer: No. Catch blocks must immediately follow their associated try block, optionally followed by a finally block.
Q9. Can two catch blocks have the same exception type?
Answer: Two identical exception types in the same sequence are generally invalid because the later handler is unreachable.
Q10. Does finally execute after a catch block?
Answer: Normally, yes. A finally block is used for cleanup when control leaves the try-catch structure, although abrupt JVM termination can prevent it from executing.
19. Quick Revision Checklist
- A single try block can have multiple catch blocks.
- Each catch block specifies an exception type.
- Only the first compatible handler executes for a particular exception.
- Catch blocks should be ordered from specific to general.
- A general handler such as
catch (Exception e) can be used as a fallback.
- Use multi-catch when unrelated exception types need the same handling logic.
- If no handler matches, the exception propagates.
- Use meaningful error messages and avoid empty catch blocks.
- Use finally or try-with-resources for appropriate cleanup tasks.
20. Conclusion
Multiple catch blocks make Java exception handling more organized and flexible. By assigning different handlers to different exception types, developers can respond appropriately to invalid input, arithmetic failures, array-access problems, and other runtime issues.
Always order catch blocks carefully, handle only exceptions that can be managed meaningfully, and avoid hiding unexpected failures. Practicing multiple catch blocks alongside multi-catch and finally will help you write clearer and more reliable Java applications.
Continue learning Java exception handling through the Core Java Training Course, register for a course demo, or visit the JustAcademy website.